package com.example.common.sdk.extend

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.common.sdk.function.IUiTips
import com.example.common.sdk.entity.UIResult

typealias UIResultLiveData<T> = LiveData<UIResult<T>>
typealias UIResultMutableLiveData<T> = MutableLiveData<UIResult<T>>

inline fun <T> UIResultLiveData<T>.observerWithResult(
    owner: LifecycleOwner,
    view: IUiTips? = null,
    showLoading: Boolean = false,
    crossinline onLoading: () -> Unit = {
        if (showLoading)
            view?.showLoading()
    },
    crossinline onCompletion: () -> Unit = {
        if (showLoading)
            view?.hideLoading()
    },
    crossinline onError: (code: Int, msg: String) -> Unit = { code: Int, msg: String ->
        view?.toast(msg)
    },
    crossinline onSuccess: (data: T?) -> Unit = { data: T? -> }
) {
    observe(owner) { uiResult ->
        when (uiResult.status) {
            UIResult.Status.Completion -> onCompletion.invoke()
            UIResult.Status.Error -> onError(uiResult.code, uiResult.msg)
            UIResult.Status.Load -> onLoading.invoke()
            UIResult.Status.Success -> onSuccess(uiResult.data)
        }

    }
}